<?php

namespace Dcat\Admin\GridCategory;

use Closure;
use Dcat\Admin\GridCategory\Grid\Tools\CategoryTree;
use Dcat\Admin\Grid as AdminGrid;
use Dcat\Admin\Support\Helper;
use Dcat\Admin\Admin;
class Grid extends AdminGrid
{

    /**
     * View for grid to render.
     *
     * @var string
     */

    public CategoryTree $_categorytree;
    protected $view = 'chinahacker.grid-category::table';

    public function __construct($repository = null, ?\Closure $builder = null, $request = null)
    {
    
        parent::__construct($repository, $builder, $request);
        
    }
    public function CategoryTree(\Closure $closure = null)
    {
        if ($closure === null) {
            return $this->_categorytree;
        }

        $this->_categorytree = new CategoryTree($this);

        call_user_func($closure, $this->_categorytree);
     
      
        return $this;
    }

  

    public function CategoryTreerender()
    {
        return $this->_categorytree->render();
    }
    /**
     * Process the grid filter.
     *
     * @param bool $toArray
     *
     * @return Collection
     */
    public function processFilter()
    {
        $this->callBuilder();
        $this->handleExportRequest();

        $this->applyQuickSearch();
        $this->applyColumnFilter();
        $this->applySelectorQuery();
        $this->applyCategoryTreerQuery();
        return $this->filter->execute();
    }
    protected function applyCategoryTreerQuery()
    {
        if (is_null($this->_categorytree)) {
            return $this;
        }

        $active = $this->_categorytree->parseSelected();
        $tree = $this->_categorytree->all();
        $tree->each(function ($selector, $column) use ($active) {
            $key = $this->_categorytree->formatKey($column);

            if (!array_key_exists($key, $active)) {
                return;
            }

            $this->fireOnce(new Grid\Events\ApplyCategoryTree([$active]));

            $values = $active[$key];
           
            Helper::withQueryCondition(
                $this->model(),
                $column,
                is_array($values) ? 'whereIn' : 'where',
                [$values]
            );
        });

        return $this;
    }
}
